﻿using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Models.V1;
using System.Buffers;

namespace DeviceCommons.DeviceMessages.Serialization.V1.Serializers
{
    public class DeviceMessageInfoSerializer : AbstractMessageSerializer<IDeviceMessageInfo>, IDeviceMessageInfoSerializer
    {
        public DeviceMessageInfoSerializer() : base(new DeviceMessageInfo())
        {
        }

        public override void Serializer(ArrayBufferWriter<byte> writer, IDeviceMessageInfo model)
        {
            if (string.IsNullOrEmpty(model.DID))
                throw new ArgumentNullException(nameof(model.DID), "设备ID不能为空");

            if (model.Reading == null)
                throw new ArgumentNullException(nameof(model.Reading), "读数信息不能为空");

            SerializeWithHeader(
                writer,
                headerLength: model.Length + 2,
                writeHeaderAction: w =>
                {
                    w.Write([model.Length]);
                    w.Write(model.DIDBytes);
                    w.Write([model.DeviceType]);
                },
                serializeContentAction: w =>
                {
                    new DeviceMessageInfoReadingsSerializer().Serializer(w, model.Reading);
                });
        }
    }
}
